<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
// 按需引入 引入 ECharts 主模块
var echarts = require('echarts/lib/echarts')
// 引入柱状图
require('echarts/lib/chart/pie')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
import resize from './mixins/resize.js'
export default {
  name: 'PieChart',
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    color: {
      type: Array,
      default: () => {
        return ['#f6da22', '#bbe2e8', '#6cacde']
      }
    },
    legend: {
      type: Object,
      default: () => {
        return {
          orient: 'vertical',
          right: -50,
          top: 50
        }
      }
    },
    tooltip: {
      type: Object,
      default: () => {
        return {}
      }
    },
    seriesObj: {
      type: Object,
      default: () => {
        return {
          name: 'Access From',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['30%', '50%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 1048, name: 'Search Engine' },
            { value: 735, name: 'Direct' }
          ]
        }
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    seriesObj: {
      handler() {
        this.setOptions()
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el)
      this.setOptions()
    },
    setOptions() {
      const chartObj = {}
      chartObj.tooltip = this.tooltip
      chartObj.color = this.color
      chartObj.legend = this.legend
      chartObj.series = []
      chartObj.series.push(this.seriesObj)
      this.chart.setOption(chartObj)
    }
  }
}
</script>
